package com.zcm.cronhelper;

import com.intellij.lang.documentation.DocumentationProviderEx;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.Nullable;
import org.quartz.CronExpression;

import java.text.SimpleDateFormat;
import java.util.Date;



public class MouseListener extends DocumentationProviderEx {
    @Override
    public @Nullable String generateDoc(PsiElement element, @Nullable PsiElement originalElement) {
        StringBuilder expression = null;
        try {
            String cron = extractText(originalElement.getText());
            CronExpression cronExpression = new CronExpression(cron);
            if (!cronExpression.isValidExpression(cron)) {
                return null;
            }

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // get next 5 time to exec
            Date cur = new Date();
            expression = new StringBuilder();
            for (int i = 0; i < 5; i++) {
                Date nextValidTimeAfter = cronExpression.getNextValidTimeAfter(cur);
                expression.append(format.format(nextValidTimeAfter) + "<br/>");
                cur = nextValidTimeAfter;
            }
        } catch (Throwable e) {
            System.out.println(e.getMessage());
        }

        return expression == null ? null : expression.toString();
    }

    protected String extractText(String rawText) {
        return rawText.strip().replace("\"", "");
    }
}
